<template>
	<view class="login-view">
		<view class="camera-box">
			<!-- #ifdef MP -->
			<camera class="camera" mode="normal" device-position="front" flash="auto"></camera>
			<!-- #endif -->
			<image :src="imgSrc" v-show="imgSrc" class="img-src" mode="widthFix"></image>
		</view>

		<view class="fiexd-btm"><u-button type="error" @click="takePhoto">拍照</u-button></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			imgSrc: ''
		};
	},
	onLoad() {
		this.$logout();
	},
	methods: {
		takePhoto() {
			const cameraContext = uni.createCameraContext();
			cameraContext.takePhoto({
				quality: 'high',
				success: (res) => {
					// this.imgSrc = res.tempImagePath;
					uni.getFileSystemManager().readFile({
						filePath: res.tempImagePath,
						encoding: 'base64',
						success: (res) => {
							let avatarBase64 = res.data;
							this.responseFun(avatarBase64);
						}
					});
				}
			});
			// cameraContext.onCameraFrame(frame => {
			// 	console.log(frame.data instanceof ArrayBuffer, frame.width, frame.height);
			// 	wx.initFaceDetect({
			// 		success: data => {
			// 			console.log(data);
			// 			wx.faceDetect({
			// 				frameBuffer: frame.data,
			// 				width: frame.width,
			// 				height: frame.height,
			// 				success: e => {
			// 					console.log(e);
			// 					this.responseFun(this.imgSrc);
			// 				},
			// 				fail: e => {
			// 					console.log(e);
			// 				}
			// 			});
			// 		}
			// 	});
			// });
		},
		responseFun(img) {
			let username = uni.getStorageSync('username');
			if (username) {
				let data = {
					faceImage: img,
					loginName: username
				};
				this.$request('/face/login', data, {
					content: 'application/x-www-form-urlencoded',
					load: true
				}).then((res) => {
					if (!res.data.Authorization) {
						this.$msg('登录失败');
						return false;
					}
					let userInfo = res.data;
					this.$store.commit('login', userInfo);

					uni.switchTab({
						url: '/pages/index/index'
					});
				});
			} else {
				this.$msg('没有用户信息，请用账号登录一次！');
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}, 500);
			}
		}
	}
};
</script>

<style lang="scss">
.login-view {
	min-height: 100vh;
	overflow: hidden;
	background: #fff;
}

.camera-box {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
}

.camera {
	width: 100%;
	height: 100%;
}

.img-src {
	width: 100%;
	height: 100%;
	position: absolute;
	left: 50%;
	top: 50%;
	z-index: 100;
	transform: translate(-50%, -50%);
}
</style>
